package com.itobase.questionnaire.service.impl;

import com.itobase.questionnaire.VO.ContentVO;
import com.itobase.questionnaire.model.*;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.SectionRateRepository;
import com.itobase.questionnaire.repository.SubmitRepository;
import com.itobase.questionnaire.repository.UserRepository;
import com.itobase.questionnaire.service.IOutcomeService;
import com.itobase.questionnaire.service.IUserService;
import com.itobase.questionnaire.template.Constant;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined.*;

/**
 * @author liucong
 * @date 2018/10/27
 */
@Service
public class OutcomeService implements IOutcomeService {

    @Autowired
    IUserService userService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    SubmitRepository submitRepository;

    @Autowired
    SectionRateRepository sectionRateRepository;



    /**
     * 传入一个submission，计算一个问卷的满意度
     * @return
     */
    @Override
    public Float calculateRate(Submission submission){

        float a = 0,b = 0;

        Map<Integer,String> answers = submission.getAnswer();
        String firstAns = answers.get(4);
        String fifthAns = answers.get(8);
/*
        switch (firstAns){
            case "A":
                a = 1.2f;
                break;
            case "B":
                a = 0.7f;
                break;
            case "C":
                a = 0.5f;
                break;

        }
*/

        switch (fifthAns){
            case "A.非常满意":
                b = 5;
                break;
            case "B.满意":
                b = 4;
                break;
            case "C.基本满意":
                b = 3;
                break;
            case "D.不满意":
                b = 2;
                break;
            case "E.很不满意":
                b = 1;
                break;
        }
        //在学生填写的问卷中，第一题作废
        User user = Optional.ofNullable(userRepository.findOne(submission.getUserId())).orElseThrow(()->new RuntimeException("绑定的用户id错误"));
        if(user.getUserTypeId().equals(Constant.TEACID)){
            //System.out.println("教师");
            return b;
        }else if(user.getUserTypeId().equals(Constant.STUID) || user.getUserTypeId().equals(Constant.GRADUATE_STUDENT_ID)){
            if(firstAns.equals("B.不熟悉")){
                return 0f;
            }else{
                return b;
            }
        }else{
            return 0f;
        }

    }


    /**
     * 创建表头单元格样式
     *
     * @param workbook
     * @return
     */
    @Override
    public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 11);
        //字体加粗
        font.setBold(true);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(BLACK.getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(true);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        return style;

    }

    /**
     * 创建数据的单元格格式
     *
     * @param workbook
     * @return
     */
    @Override
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 10);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(BLACK.getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(BLACK.getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(BLACK.getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(BLACK.getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        return style;

    }

    public void writeToResponse(HttpServletResponse response, HSSFWorkbook workbook,String excelName) {
        if (workbook != null) {
            try {
                String fileName = new String(excelName.getBytes(), StandardCharsets.ISO_8859_1)  + ".xls";
                String headStr = "attachment;filename=" + fileName;
                response.setContentType("APPLICATION/OCTET-STREAM");
                response.setHeader("Content-Disposition", headStr);
                OutputStream out = response.getOutputStream();
                workbook.write(out);
                workbook.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getSurveyContentRate(Survey survey) {
        String sectionName = Optional.ofNullable(survey.getSection()).orElseThrow(()->new RuntimeException("该调查未绑定调查部门"));
        SectionRate sectionRate = sectionRateRepository.findBySectionName(sectionName);
        List<Submission> submissionList = submitRepository.findBySurveyId(survey.getId());
        /*
        <type,《人数，总分》；
         */
        Map<String,Float> typeRate = sectionRate.getTypeRate();
        float totalRate=0;
        Map<String, ContentVO> totalKinds = new HashMap<>();
        for (Submission submission : submissionList) {
            Map<String, String> outcome = submission.getOutcome();
            for (String type : outcome.keySet()) {
                Float personContent = Float.parseFloat(outcome.get(type));
                if(totalKinds.containsKey(type)&&personContent!=0){
                    ContentVO contentVO = totalKinds.get(type);
                    contentVO.personCountPlus();
                    contentVO.gradePlus(personContent);
                    totalKinds.put(type,contentVO);
                }else if(personContent!=0){
                    ContentVO contentVO = new ContentVO(1,personContent);
                    totalKinds.put(type,contentVO);
                }

            }
        }
        for(String type:totalKinds.keySet()){
            ContentVO contentVO = totalKinds.get(type);
            Float average = contentVO.getPartGrade()/contentVO.getPersonCount();
            if(typeRate.get(type)==null) {
                throw new RuntimeException("由于人员所属调查组不存在已有数据库内，无法获取满意度");
            }else {
                totalRate+=average*typeRate.get(type);
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        return String.valueOf(decimalFormat.format(totalRate));

    }


}
